using System;
using ServiceStack.ServiceHost;
using ODSWebService.DTO.Requests;
using log4net;
using ODSWebService.DTO.Responses;
using ODSWebService.DTO;
using ODSearchEngine;
using System.Collections.Generic;

namespace ODSWebService.Services
{
	public class SearchService : IService<SearchRequest>
	{
		private static readonly ILog logger = LogManager.GetLogger(typeof(SearchService));
		
		private ISearchEngine searchEngine = null;
		
		public SearchService()
		{
			this.searchEngine = IocManager.Get<ISearchEngine>();
			if(logger.IsDebugEnabled)
				logger.DebugFormat("Got search engine {0}.", this.searchEngine);
		}
		
		#region IService[SearchRequest] implementation
		public object Execute (SearchRequest request)
		{
			if(logger.IsDebugEnabled)
				logger.DebugFormat("Executing search. {0}", request);
			SearchResponse result = new SearchResponse();
			if(request.Keys != null && request.Keys.Length > 0)
			{
				List<SearchResult> results = new List<SearchResult>(); // TODO: Optimize		
				var hits = this.searchEngine.Search(request.Keys, request.Query);
				foreach(var hit in hits)
				{
					SearchResult sr = new SearchResult(); // TODO: Pull data and actual values
					sr.ID = hit.ID;	
					sr.Data = this.searchEngine.GetData(hit);
					results.Add(sr);
				}
				result.Results = results.ToArray();
				result.ResultsCount = (uint)result.Results.Length;
			}
			if(logger.IsDebugEnabled)
				logger.DebugFormat("Search completed with results {0}", result);
			return result;
		}
		#endregion		
	}
}

